<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type {
  OnActionClickParams,
  VxeGridListeners,
  VxeGridProps,
} from '#/adapter/vxe-table';
import type { DictApi, ToolTypeApi } from '#/api';
import type { workstationAPI } from '#/api/mes/md/workstation';

import { reactive, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { VxeButton } from '@vben/plugins/vxe-table';

import { message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { DictResp } from '#/api';
import {
  deleteWorkstation,
  getWorkstationList,
} from '#/api/mes/md/workstation';
import {
  getToolBarBtns,
  messageError,
  messageSuccess,
  PopMsg,
  setToolBarBtnDefaultDisabled,
  updateToolbarButtonStatus,
} from '#/utils';

import AddWorkstation from '../workstation/Addwork.vue';

const sys_yes_no = reactive<DictApi.SelectOption[]>([]);
// const workshopList = ref<DictApi.SelectOption[]>([]);

DictResp(['sys_yes_no']).then((res) => {
  if (res.sys_yes_no) {
    sys_yes_no.push(...res.sys_yes_no);
  }
});
const [workstationForm, modalApi] = useVbenModal({
  connectedComponent: AddWorkstation,
  showConfirmButton: false,
  showCancelButton: false,
});

const selectedRow = ref<ToolTypeApi.Row[]>([]);
const initData = {
  toolTypeId: null,
  toolTypeCode: '',
  toolTypeName: '',
  codeFlag: 'Y',
  maintenType: null,
  maintenPeriod: null,
  remark: '',
};
selectedRow.value = [initData];

interface RowType {
  searchValue: null;
  createBy: string;
  createTime: Date;
  updateBy: string;
  updateTime: Date | null;
  remark: string;
  params: any;
  workstationId: number;
  workstationCode: string;
  workstationName: string;
  workstationAddress: null;
  workshopId: number;
  workshopCode: any;
  workshopName: any;
  processId: number;
  processCode: string;
  processName: string;
  warehouseId: number;
  warehouseCode: any;
  warehouseName: any;
  locationId: number;
  locationCode: any;
  locationName: any;
  areaId: number;
  areaCode: any;
  areaName: any;
  enableFlag: any;
  attr1: null;
  attr2: null;
  attr3: number;
  attr4: number;
}

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入工作站编码',
      },
      fieldName: 'workstationCode',
      label: '工作站编号',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入工作站名称',
      },
      fieldName: 'workstationName',
      label: '工作站名称',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        // options: workshopList,
        placeholder: '请选择车间',
      },
      fieldName: 'workshopId',
      label: '所在车间名称',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        // options: processList,
        placeholder: '请选择工序',
      },
      fieldName: 'processId',
      label: '所属工序',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

const buttons = getToolBarBtns();
buttons.value.push({
  name: '导出',
  code: 'export',
  status: 'warning',
  icon: 'vxe-icon-download',
});

const gridOptions: VxeGridProps<RowType> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    { align: 'left', title: '', type: 'checkbox', width: 100 },
    {
      field: 'workstationCode',
      title: '工作站编号',
      cellRender: { name: 'CellButtonInfo', props: { onClick: onEdit } },
    },
    { field: 'workstationName', title: '工作站名称' },
    { field: 'workstationAddress', title: '工作站地点' },
    {
      field: 'workshopName',
      title: '所在车间名称',
    },
    { field: 'processName', title: '所属工序' },
    {
      field: 'enableFlag',
      title: '是否启用',
      cellRender: { name: 'CellTag' },
    },
    {
      field: 'remark',
      title: '备注',
    },
    {
      title: '操作',
      width: 150,
      slots: { default: 'operate' },
    },
  ],
  keepSource: true,
  pagerConfig: {
    enabled: true,
    slots: {
      // 自定义分页器
    },
    // 每页显示数量选择
    pageSizes: [10, 20, 50, 100],
    // 分页布局
    layouts: [
      'PrevJump',
      'PrevPage',
      'Number',
      'NextPage',
      'NextJump',
      'Sizes',
      'FullJump',
      'Total',
    ],
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const res = await getWorkstationList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
        return {
          total: res.total,
          items: res.rows,
        };
      },
    },
  },
  toolbarConfig: {
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
    refresh: true,
    buttons: buttons.value,
  },
};

// 控制modal的响应式变量
// const showPopup = ref(false);

/**
 * 编辑
 * @param row
 */
// function onEdit(row: ToolTypeApi.Row) {
//   selectedRows.value = [row];
//   showPopup.value = true;
// }
function onEdit(row: workstationAPI.Row) {
  modalApi
    .setData({ row }) // 传入要编辑的数据
    .setState({
      title: '编辑工作站',
    })
    .open();
}

/**
 * 创建
 */
function onAdd() {
  modalApi
    .setData({ row: {} })
    .setState({
      title: '新增工作站',
    })
    .open();
}

/**
 * 删除
 * @param row
 */

function onDelete(data: workstationAPI.Row | workstationAPI.Row[]) {
  const ids = Array.isArray(data)
    ? data.map((item) => item.workstationId)
    : [data.workstationId];
  const idString = ids.join(',');
  PopMsg(`确定要删除客户编号编号为【${idString}】的数据吗？`, '提示', 'warn')
    .then(() =>
      deleteWorkstation(idString)
        .then(() => {
          messageSuccess(`删除成功`);
          refreshGrid();
        })
        .catch((error) => {
          messageError(error);
        }),
    )
    .catch(() => {
      // 用户点击取消
      message.info('已取消删除');
    });
}

// 存储选中行的响应式变量
const selectedRows = ref<any[]>([]);

// 表格事件
const gridEvents: VxeGridListeners = {
  toolbarButtonClick({ code }) {
    // console.warn(code);
    switch (code) {
      case 'myAdd': {
        // 新增逻辑
        onAdd();
        // modalApi.open();
        break;
      }
      case 'myDel': {
        if (selectedRows.value.length > 0) {
          onDelete(selectedRows.value);
        }
        break;
      }
      case 'myEdit': {
        // 修改逻辑
        if (selectedRows.value.length > 1) {
          // eslint-disable-next-line no-alert
          confirm('请选择单行');
        } else {
          onEdit(selectedRows.value[0] as any);
        }
        break;
      }
      default: {
        break;
      }
    }
    updateToolbarButtonStatus(selectedRows); // 更新按钮状态
  },
  checkboxChange() {
    selectedRows.value = gridApi?.grid?.getCheckboxRecords();
    setToolBarBtnDefaultDisabled(buttons, selectedRows.value.length);
  },
  checkboxAll() {
    selectedRows.value = gridApi?.grid?.getCheckboxRecords();
    setToolBarBtnDefaultDisabled(buttons, selectedRows.value.length);
  },
};
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});

/**
 * 处理表格操作列点击事件的函数
 *
 * @param  - 包含操作代码和行数据的对象
 */

function onActionClick({ code, row }: OnActionClickParams<workstationAPI.Row>) {
  switch (code) {
    case 'myDel': {
      onDelete(row);
      break;
    }
    case 'myEdit': {
      onEdit(row);
      break;
    }
  }
  updateToolbarButtonStatus(selectedRows); // 更新按钮状态
}

// 刷新表格
function refreshGrid() {
  gridApi?.query();
}
</script>

<template>
  <div class="vp-raw w-full">
    <Grid>
      <template #operate="{ row }">
        <VxeButton
          mode="text"
          status="primary"
          icon="vxe-icon-signature"
          @click="onActionClick({ code: 'myEdit', row })"
        >
          修改
        </VxeButton>
        <VxeButton
          mode="text"
          status="error"
          icon="vxe-icon-delete"
          @click="onActionClick({ code: 'myDel', row })"
        >
          删除
        </VxeButton>
      </template>
    </Grid>
    <workstationForm @success="refreshGrid" class="w-[700px]" />
  </div>
</template>
